﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace SydEnergiDataService
{
    public class SydEnergiDataServiceDbContainer : ObjectContext
    {
        private ObjectSet<AddressDto> _addressDtos;
        private ObjectSet<CabinetDto> _cabinetDtos;
        private ObjectSet<EntryDto> _entryDtos;
        private ObjectSet<HistoryEntryDto> _historyEntryDtos;
 
        public SydEnergiDataServiceDbContainer()
            : base("name=SydEnergiDataServiceDbContainer", "SydEnergiDataServiceDbContainer")
        {
            _historyEntryDtos = CreateObjectSet<HistoryEntryDto>();
            _addressDtos = CreateObjectSet<AddressDto>();
            _cabinetDtos = CreateObjectSet<CabinetDto>();
            _entryDtos = CreateObjectSet<EntryDto>();
        }

        public ObjectSet<AddressDto> AddressDtos { get { return _addressDtos; } }
        public ObjectSet<CabinetDto> CabinetDtos { get { return _cabinetDtos; } }
        public ObjectSet<EntryDto> EntryDtos { get { return _entryDtos; } }
        public ObjectSet<HistoryEntryDto> HistoryEntryDtos { get { return _historyEntryDtos; } }

        public void AddCabinet(CabinetDto entity)
        {
            CabinetDtos.AddObject(entity);
        }

        public void DeleteCabinet(CabinetDto entity)
        {
            var c = CabinetDtos.Single(cab => cab.CabinetId == entity.CabinetId);
            var entries = EntryDtos.Where(e => e.CabinetId == c.CabinetId).ToList();

            for (var i = 0; i < entries.Count; i++)
            {
                var entry = entries.Skip(i).First();
                var historyEntries = HistoryEntryDtos.Where(h => h.EntryDtoId == entry.Id).ToList();
                for (var j = 0; j < historyEntries.Count; j++)
                {
                    HistoryEntryDtos.DeleteObject(historyEntries.Skip(j).First());
                }
                AddressDtos.DeleteObject(entries.ElementAt(i).AddressDto);
                EntryDtos.DeleteObject(entries.ElementAt(i));
            }

            AddressDtos.DeleteObject(c.AddressDto);
            CabinetDtos.DeleteObject(c);

            SaveChanges();
        }
 
        
    }
}
